<?php

namespace App\Services;

use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use TencentCloud\Common\CommonClient;
use TencentCloud\Common\Credential;

class ASRService
{
    /**
     * @throws \TencentCloud\Common\Exception\TencentCloudSDKException
     * @throws Exception
     */
    static public function audioToText(string $audioFilePath) : string
    {
        $fileContent = file_get_contents(storage_path("app/" . $audioFilePath));
        if (!$fileContent) {
            throw new Exception("Failed to get the file!");
        }
        $cred = new Credential(config("app.qcloud_secret_id"), config("app.qcloud_secret_key"));
        $client =  new CommonClient("asr", "2019-06-14", $cred, "ap-guangzhou");
        $body = [
            'EngineModelType' => "16k_zh",
            'ChannelNum' => 1,
            'ResTextFormat' => 0,
            'SourceType' => 1,
            'Data' => base64_encode($fileContent)
        ];
        $resp = $client->callJson("CreateRecTask", $body);
        // Log::info(json_encode($resp));
        $taskId = Arr::get($resp, "Data.TaskId", 0);
        if (!$taskId) {
            Log::error("音频转文字CreateRecTask失败");
            throw new Exception("音频转文字CreateRecTask失败");
        }
        Log::info("TaskId:" . $taskId);
        for($i = 0 ; $i < 8; $i++) {
            sleep(1);
            $body = [
                'TaskId' => $taskId,
            ];
            $resp = $client->callJson("DescribeTaskStatus", $body);
            // Log::info(json_encode($resp));
            $status = Arr::get($resp, "Data.Status", 0);
            if ($status == 2) {
                $result = Arr::get($resp, "Data.Result", '');
                Log::info($result);
                return trim($result);
            }
        }
        throw new Exception("音频转文字DescribeTaskStatus三次失败");
    }
}
